package com.lej.login.wxLogin

import android.graphics.Color
import android.text.SpannableStringBuilder
import android.text.method.LinkMovementMethod
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lej.core.base.BaseActivity
import com.lej.core.common.ERROR_CODE
import com.lej.core.common.PCacheInfo
import com.lej.core.daq.DAQEvent
import com.lej.core.dsl.textColor
import com.lej.core.provider.loginStatusChange
import com.lej.core.router.CRouter
import com.lej.core.utils.extention.*
import com.lej.core.utils.load
import com.lej.dataservice.club.http.REMOTE_LOGIN
import com.lej.dataservice.club.http.RESULT_SUCCESS
import com.lej.dataservice.club.http.WX_NOT_BIND
import com.lej.dataservice.club.http.base.HttpUrl
import com.lej.dataservice.club.http.bean.onError
import com.lej.dataservice.club.http.bean.onLoading
import com.lej.dataservice.club.http.bean.onSuccess
import com.lej.login.BR
import com.lej.login.R
import com.lej.login.databinding.ActivityLoginWxBinding
import com.lej.theme.toast.CustomTips.showTips
import com.lej.wx.WX_LOGIN
import com.qmuiteam.qmui.kotlin.onClick
import com.qmuiteam.qmui.util.QMUIStatusBarHelper
import com.shuyu.gsyvideoplayer.utils.GSYVideoType
import kotlinx.coroutines.launch

/**
 *  author: cjq
 *  date  : 2022/12/5 0005
 *  desc  :
 */
@Route(path = CRouter.login)
class WxLoginActivity : BaseActivity<ActivityLoginWxBinding, WxLoginVM>() {
    override fun getLayout(): Int = R.layout.activity_login_wx

    override fun initVariableId(): Int = BR.vm

    private var nowState: Int = LOGIN_WX  //当前所在状态
    private var lastState: Int = LOGIN_WX  //返回状态
    override fun initData() {
        super.initData()
        loginStatusChange.forEach { it(false) }
        cleanData()
        QMUIStatusBarHelper.translucent(this)
        QMUIStatusBarHelper.setStatusBarDarkMode(this)

        val errorCode = intent.getIntExtra(ERROR_CODE, -1)   //是否第一次进入，修改对应布局
        if (errorCode == REMOTE_LOGIN) {
            showTips("登录已失效\n您的帐号已在另一台设备登录", isFail = true)
        }
        binding.tvAgreement.setLink()
        binding.tvAgreementTel.setLink()
        viewModel.getLoginVideo(versionName).onSuccess(this) {
            initPlayer(it)
        }

        binding.tvVersion.text = "版本号：v$versionName"

        initClick()
        registerObserver()

    }

    private fun initClick(){
        binding.ivLogin.onClick {
            viewModel.pullWX(this)
        }

        binding.tvChangeWx.onClick {
            changeState(LOGIN_WX)
            viewModel.stopCode()
        }

        binding.tvChangeTel.onClick {
            changeState(LOGIN_TEL)
        }

        binding.tvTelNext.onClick {
            nextOnClick()
        }

        binding.ivClose.onClick {
            changeState(lastState)
            viewModel.stopCode()
        }

        binding.tvVerify.onClick {
            lifecycleScope.launch {
                viewModel.sendCode(nowState)
            }
        }

        binding.viewWxClick.onClick {
            val value = viewModel.wxCheckStatus.value?:true
            viewModel.wxCheckStatus.value = !value
        }

        binding.viewTelClick.onClick {
            val value = viewModel.telCheckStatus.value?:true
            viewModel.telCheckStatus.value = !value
        }
    }

    private fun registerObserver() {
        LiveEventBus.get<String>(WX_LOGIN).observe(this) {
            lifecycleScope.launch {
                val code = viewModel.wechatLogin(it) ?: return@launch
                if (code == RESULT_SUCCESS) {
                    judgeName()
                } else if (code == WX_NOT_BIND) {
                    changeState(LOGIN_BIND_TEL)
                }
            }
        }
    }

    private fun nextOnClick() {
        when (nowState) {
            LOGIN_TEL -> {
                // 手机号登录
                viewModel.loginTel()?.onSuccess(this) { it ->
                    disDialog()
                    viewModel.loginRes = it
                    PCacheInfo.token = it.login_token?:""
                    judgeName()
                }?.onError(this) { itt ->
                    disDialog()
                    itt.message.toast()
                }?.onLoading(this){showLoading()}
            }
            LOGIN_BIND_NAME -> {
                // 绑定用户名
                viewModel.bindName()?.onSuccess(this){
                    disDialog()
                    PCacheInfo.nick = binding.etName.text.toString()
                    toMain()
                    viewModel.loginRes?.nick = viewModel.userName.value
                }?.onError(this){
                    disDialog()
                    binding.tvTitle.text = it.message
                    binding.tvTitle.textColor = getColor(R.color.themeErrorColor)
                }?.onLoading(this){showLoading()}
            }
            LOGIN_BIND_TEL -> {
                viewModel.bindTel()?.onSuccess(this) {
                    disDialog()
                    viewModel.loginRes = it
                    PCacheInfo.token = it.login_token?:""
                    judgeName()
                }?.onError(this) {
                    disDialog()
                    it.message.toast()
                }?.onLoading(this){showLoading()}
            }
        }
    }

    private fun changeState(state: Int) {
        nowState = state
        when (state) {
            LOGIN_TEL -> {
                lastState = LOGIN_TEL
                // 手机号登录
                changeViewState()
            }
            LOGIN_BIND_NAME -> {
                // 绑定用户名
                changeViewState()
                viewModel.loginRes?.avatar?.let { load(it, binding.ivLoginHead) }
                viewModel.loginRes?.wechat_nick?.let { binding.etName.setText(it) }
            }
            LOGIN_WX -> {
                lastState = LOGIN_WX
                // 微信登录页面
                binding.clTel.isVisible = false
                binding.clWx.isVisible = true
                binding.tvChangeWx.isVisible = false
            }
            LOGIN_BIND_TEL -> {
                changeViewState()
            }
        }
    }

    private fun changeViewState(){
        viewModel.userPhone.value = ""
        viewModel.userVerify.value = ""
        viewModel.sendCodeEvent.value = "获取"
        binding.clWx.isVisible = false   //首页
        binding.clTel.isVisible = true   //手机号大界面
        binding.ivClose.isVisible = nowState == LOGIN_BIND_TEL  //关闭按钮
        binding.groupTel.isVisible = (nowState ==LOGIN_TEL || nowState == LOGIN_BIND_TEL)   //手机号输入框
        binding.groupLoginTel.isVisible = nowState == LOGIN_TEL //手机号服务协议和logo
        binding.groupName.isVisible = nowState == LOGIN_BIND_NAME //用户头像和昵称
        binding.tvBindTelTips.isVisible = nowState == LOGIN_BIND_TEL //手机号绑定提示
        binding.tvTitle.text = "提示" //标题
        binding.tvTitle.isVisible = (nowState ==LOGIN_BIND_NAME || nowState == LOGIN_BIND_TEL)
        binding.tvTelNext.isVisible = true //下一步按钮
        binding.tvTelNext.text = "下一步"
        binding.tvChangeWx.isVisible = nowState == LOGIN_TEL  //切换微信按钮
    }

    /**
     * 判断进入绑定用户页还是进入主页
     */
    private fun judgeName() {
        if (viewModel.loginRes?.nick.isNullOrEmpty()) {
            //绑定用户名
            changeState(LOGIN_BIND_NAME)
        } else {
            //主页
            PCacheInfo.nick = viewModel.loginRes?.nick ?: ""
            toMain()
        }
    }

    private fun toMain() {
        "登录成功".toast()
        PCacheInfo.firstInstall = false
        PCacheInfo.headImg = viewModel.loginRes?.avatar?:""
        PCacheInfo.token = viewModel.loginRes?.login_token?:""
        router(CRouter.newMain)
        loginStatusChange.forEach { it(true) }
        finish()
    }

    private fun showPrivacy(url: String) {
        DAQEvent.login_see_protocol.mobEvent()
        toLink(url)
    }

    private fun initPlayer(source: String) {
        GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_FULL)
        binding.gsoPlayer.apply {
            setUpLazy(source, true, cacheDir, null, "")
            isLooping = true
            startPlayLogic()
        }
    }

    override fun onResume() {
        super.onResume()
        binding.gsoPlayer.onVideoResume()
    }

    override fun onPause() {
        super.onPause()
        binding.gsoPlayer.onVideoPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.gsoPlayer.release()
    }

    private fun TextView.setLink() {
        highlightColor = Color.TRANSPARENT
        this.movementMethod = LinkMovementMethod.getInstance()
        this.text = SpannableStringBuilder("我已阅读并同意")
            .append("《服务协议》".textLinkClick { showPrivacy(HttpUrl.USER_AGREEMENT_URL) })
            .append("和")
            .append("《隐私协议》".textLinkClick { showPrivacy(HttpUrl.PERMISSION_URL) })
    }

    override fun onBackPressed() {
        moveTaskToBack(true)
    }

    private fun cleanData() {
        PCacheInfo.cleanUserInfo()
    }
}